package com.atguigu.dataSource;

import com.atguigu.pojo.Customer;
import com.hjw.jdbc.DBUtils;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * commons-dbutils是Apache组织提供的一个开源的JDBC工具类库，封装了对数据库的crud操作
 *
 * @author hjwStrart
 * @time 2022-03-10 15:59
 * @version: 1.0
 */
public class ApacheDBUtilsTest {
    public static void main(String[] args) {

        try {
            test3();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //    QueryRunner是DBUtils提供的主要工具类，update用于增删改操作
    private static void test1() throws SQLException {

        QueryRunner queryRunner = new QueryRunner();
        Connection conn8 = DBUtils.getConn8();
        int i = queryRunner.update(conn8, "delete from user_table where user = ?", "DD");
        System.out.println(i);
    }

    //    query用于查询操操作
//    若对DBUtils提供的ResultSetHandler不满意，可以通过实现此接口自定义实现类
//    ResultSetHandler接口：定义了查询返回类型的规范。实现类如下：
//        BeanHandler:返回一个对象
//        BeanListHandler：返回一个对象集合
//        MapHandler:返回一个map，对应一条记录（ 属性名作为key，值作为value）
//        MapListHandler：返回一个map集合
    private static void test2() throws SQLException {

        QueryRunner queryRunner = new QueryRunner();
        BeanHandler<Customer> beanHandler = new BeanHandler<Customer>(Customer.class);
        Connection conn8 = DBUtils.getConn8();
        Customer customer = queryRunner.query(conn8, "select * from customers  where id = ?", beanHandler, 1);
        System.out.println(customer);
//        BeanListHandler<Customer> beanHandler = new BeanListHandler<Customer>(Customer.class);
//        Connection conn8 = DBUtils.getConn8();
//        List<Customer> customers = queryRunner.query(conn8, "select * from customers", beanHandler);
    }

    //    查询特殊字段：例如总记录数、最大值等
//      ScalarHandler
    private static void test3() throws SQLException {
        Connection conn8 = DBUtils.getConn8();
        String sql = "select count(*) from customers";
        ScalarHandler<Object> scalarHandler = new ScalarHandler<>();
        QueryRunner queryRunner = new QueryRunner();
        Object query = queryRunner.query(conn8,sql, scalarHandler);
        System.out.println(query);

    }

//    DBUtils资源的关闭,其内部提供了DbUtils工具类，实现资源的关闭
    private static void test4(Connection conn){
        try {
            DbUtils.close(conn);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        DbUtils.closeQuietly(conn);
    }

}
